package com.ruoyi.station.controller;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.oiltank.domain.OilTank;
import com.ruoyi.oiltank.service.IOilTankService;
import com.ruoyi.report.domain.ReportCarInfo;
import com.ruoyi.report.mapper.ReportCarInfoMapper;
import com.ruoyi.station.domain.RateDTO;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.station.domain.ReportGasStation;
import com.ruoyi.station.service.IReportGasStationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 航空加油站数据上报Controller
 *
 * @author ruoyi
 * @date 2024-09-23
 */
@RestController
@RequestMapping("/station/station")
public class ReportGasStationController extends BaseController {
    @Autowired
    private IReportGasStationService reportGasStationService;
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private IOilTankService oilTankService;

    /**
     * 查询航空加油站数据上报列表
     */
    @PreAuthorize("@ss.hasPermi('station:station:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportGasStation reportGasStation) {
        startPage();
        List<ReportGasStation> list = reportGasStationService.selectReportGasStationList(reportGasStation);
        return getDataTable(list);
    }

    @GetMapping("/listNoAuth")
    public TableDataInfo listNoAuth(ReportGasStation reportGasStation) {
        startPage();
        List<ReportGasStation> list = reportGasStationService.selectReportGasStationList(reportGasStation);
        return getDataTable(list);
    }
    @GetMapping("/listNoAuthPage")
    public TableDataInfo listNoAuthPage(ReportGasStation reportGasStation) {
//        startPage();
        List<ReportGasStation> list = reportGasStationService.selectReportGasStationList(reportGasStation);
        return getDataTable(list);
    }
    @Autowired
    private ReportCarInfoMapper carInfoMapper;

    /**
     * 导出航空加油站数据上报列表
     */
    @PreAuthorize("@ss.hasPermi('station:station:export')")
    @Log(title = "航空加油站数据上报", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportGasStation reportGasStation) {
        List<OilTank> oilTanks = oilTankService.selectOilTankList(new OilTank());
        Gson gson = new Gson();
        List<ReportGasStation> list = reportGasStationService.selectReportGasStationList(reportGasStation);
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        List<ReportCarInfo> cars = carInfoMapper.selectReportCarInfoList(new ReportCarInfo());
        for (ReportGasStation gasStation : list) {
//            SysUser correspondingWork = sysUsers.stream()
//                    .filter(user -> user.getUserId().equals(gasStation.getWorkPerson()))
//                    .findFirst()
//                    .orElse(null);
//            gasStation.setWorkName(ObjectUtil.isNotEmpty(correspondingWork) ? correspondingWork.getUserName() : "");
            String extra2 = gasStation.getExtra2();
            Type userType = new TypeToken<List<Long>>() {}.getType();
            List<Long> uids = gson.fromJson(extra2, userType);

            List<SysUser> correspondingReports = sysUsers.stream()
                    .filter(user -> uids.contains(user.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                    .collect(Collectors.toList());

            String workNames = correspondingReports.stream()
                    .map(SysUser::getUserName)
                    .collect(Collectors.joining(", "));

            gasStation.setWorkName(workNames);

            SysUser correspondingReport = sysUsers.stream()
                    .filter(user -> user.getUserId().equals(gasStation.getReportPerson()))
                    .findFirst()
                    .orElse(null);
            ReportCarInfo carInfo = cars.stream()
                    .filter(car -> car.getId().equals(gasStation.getCarId()))
                    .findFirst()
                    .orElse(null);
            gasStation.setCarInfo(ObjectUtil.isNotEmpty(carInfo) ? carInfo.getName() + "[" + carInfo.getLicensePlate() + "]" : "");
            OilTank tankInfo = oilTanks.stream()
                    .filter(tank -> tank.getId().equals(gasStation.getTankId()))
                    .findFirst()
                    .orElse(null);
            gasStation.setTankName(ObjectUtil.isNotEmpty(tankInfo) ? tankInfo.getName() : "");


            OilTank dirtyTankInfo = oilTanks.stream()
                    .filter(tank -> tank.getId().equals(gasStation.getDirtyTankId()))
                    .findFirst()
                    .orElse(null);
            gasStation.setDirtyTankName(ObjectUtil.isNotEmpty(dirtyTankInfo) ? dirtyTankInfo.getName() : "");


            gasStation.setReportName(ObjectUtil.isNotEmpty(correspondingReport) ? correspondingReport.getUserName() : "");

            String rateJson = gasStation.getRateJson();
            if (StringUtils.isNotEmpty(rateJson)) {
                Type listType = new TypeToken<List<RateDTO>>() {
                }.getType();

                List<RateDTO> rateList = gson.fromJson(rateJson, listType);
                String concatenatedNames = rateList.stream()
                        .map(a -> {
                            return a.getLevel() + "密：(温度:" + a.getTemperature() + ";密度：" + a.getDensity() + ")";

                        })  // Replace getRateName() with the actual getter
                        .collect(Collectors.joining(", "));
                gasStation.setRateName(concatenatedNames);
            }
        }


        ExcelUtil<ReportGasStation> util = new ExcelUtil<ReportGasStation>(ReportGasStation.class);
        util.exportExcel(response, list, "航空加油站数据上报数据");
    }

    /**
     * 获取航空加油站数据上报详细信息
     */
    @PreAuthorize("@ss.hasPermi('station:station:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(reportGasStationService.selectReportGasStationById(id));
    }

    @Autowired
    private TokenService tokenService;

    /**
     * 新增航空加油站数据上报
     */
    @PreAuthorize("@ss.hasPermi('station:station:add')")
    @Log(title = "航空加油站数据上报", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportGasStation reportGasStation) {
        List<Map> rate = reportGasStation.getRate();
        Gson gson = new Gson();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        reportGasStation.setDeptId(loginUser.getUser().getDept().getDeptId());
        reportGasStation.setRateJson(gson.toJson(rate));
        reportGasStation.setCreateTime(DateUtils.getNowDate());

        Integer i = reportGasStationService.countTodayRecordsStation(reportGasStation.getDeptId());
        if (i>=1){
            throw new RuntimeException("今日已有数据上报记录,请前往修改");
        }


        List<Long> workUsers = reportGasStation.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)) {
            reportGasStation.setExtra2(gson.toJson(workUsers));
        }
        List<Long> cars = reportGasStation.getCars();
        if (CollectionUtil.isNotEmpty(cars)){
            reportGasStation.setCarId(gson.toJson(cars));
        }
        return toAjax(reportGasStationService.insertReportGasStation(reportGasStation));
    }

    /**
     * 修改航空加油站数据上报
     */
    @PreAuthorize("@ss.hasPermi('station:station:edit')")
    @Log(title = "航空加油站数据上报", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportGasStation reportGasStation) {
        List<Map> rate = reportGasStation.getRate();
        Gson gson = new Gson();

        reportGasStation.setRateJson(gson.toJson(rate));

        List<Long> cars = reportGasStation.getCars();
        if (CollectionUtil.isNotEmpty(cars)){
            reportGasStation.setCarId(gson.toJson(cars));
        }
        return toAjax(reportGasStationService.updateReportGasStation(reportGasStation));
    }

    /**
     * 删除航空加油站数据上报
     */
    @PreAuthorize("@ss.hasPermi('station:station:remove')")
    @Log(title = "航空加油站数据上报", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(reportGasStationService.deleteReportGasStationByIds(ids));
    }
}
